package demo0910;

class MyBlockingQueue {
    private int[] queue = new int[1000];
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    public void put(int val) throws InterruptedException {
        synchronized (this) {
            while (isFull()) {
                wait();
            }
            queue[tail] = val;
            tail = (tail + 1) % queue.length;
            size++;
            notifyAll();
        }
    }

    public int take() throws InterruptedException {
        int result = 0;
        synchronized (this) {
            while (isEmpty()) {
                this.wait();
            }
            result = queue[head];
            head = (head + 1) % queue.length;
            size--;
            notifyAll();
            return result;
        }

    }


    public boolean isEmpty() {
        return size == 0;
    }
    public boolean isFull() {
        return size == queue.length;
    }
    public int getSize() {
        return size;
    }
}

public class T2_2_0520 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
        Thread producer = new Thread(()->{
            int n = 1;
            while (true) {
                try {
                    myBlockingQueue.put(n);
                    System.out.println(Thread.currentThread().getName()+":"+ n);
                    n++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"生产者");
        Thread consumer = new Thread(()->{
            while (true) {
                try {
                    int id = myBlockingQueue.take();
                    System.out.println(Thread.currentThread().getName()+":"+ id);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"消费者");
        producer.start();
        consumer.start();
    }
}
